package bluetooth;

import android.telephony.TelephonyManager;
import android.widget.Toast;

import com.ecdc.soexample.App;
import com.ecdc.soexample.HomeActivity;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import ota.CheckSendDataUtils;
import ota.MyByte;
import ota.Myhex;
import ota.OtaCheckSendDataUtils;
import ota.OtaUtils;
import utils.SharedpreferencesUtils;

public class BluetoothCommandCode {

    private static BluetoothCommandCode mBluetoothCommandCode;
    private static ExecutorService executorService ;
    private static List<String> executorServiceMethod=new ArrayList<>() ;

    private Method[]methodArray;
    private static MyThread mMyThread;
    private BluetoothCommandCode() {
    }

    public static BluetoothCommandCode getCheckSendDataUtilsInstance() {
        if (mBluetoothCommandCode == null) {
            synchronized (OtaUtils.class) {
                if (mBluetoothCommandCode == null) {
                    mBluetoothCommandCode = new BluetoothCommandCode();
                    executorService = Executors.newFixedThreadPool(1);
                }
            }
        }
        return mBluetoothCommandCode;
    }
    public static BluetoothCommandCode getCheckSendDataUtilsInstance(BluettothInterface mBluettothInterface) {
        if (mBluetoothCommandCode == null) {
            synchronized (OtaUtils.class) {
                if (mBluetoothCommandCode == null) {
                    mBluetoothCommandCode = new BluetoothCommandCode();
                    executorService = Executors.newFixedThreadPool(1);

                }
            }
        }
        GattUpdateReceiver.mBluettothInterface = mBluettothInterface;

        return mBluetoothCommandCode;
    }

    public void excuteMethods(Method ...methods){
        methodArray=methods;
        if(mMyThread==null){
            mMyThread=new MyThread();
        }
        executorService.execute(mMyThread);

    }

    //设置手表时间
    public void sendSetWatchTime() {



        Calendar calendar = Calendar.getInstance();
        //获取系统的日期
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH)+1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        //0x0a 3102 07E1 09 1E 17 00 3B

        byte yearByte2= MyByte.intToByteArray(year)[MyByte.intToByteArray(year).length-1];
        byte yearByte1= MyByte.intToByteArray(year)[MyByte.intToByteArray(year).length-2];

        byte monthByte= MyByte.intToByteArray(month)[MyByte.intToByteArray(month).length-1];
        byte dayByte= MyByte.intToByteArray(day)[MyByte.intToByteArray(day).length-1];

        byte hourByte= MyByte.intToByteArray(hour)[MyByte.intToByteArray(hour).length-1];
        byte minuteByte= MyByte.intToByteArray(minute)[MyByte.intToByteArray(minute).length-1];
        byte secondByte= MyByte.intToByteArray(second)[MyByte.intToByteArray(second).length-1];

        final byte[] ENABLE_NOTIFICATION_MIX_VALUE2 = new byte[]{0x0a,
                (byte) 0x31,
                0x02,
                yearByte1,
                yearByte2,
                monthByte,
                dayByte,
                hourByte,
                minuteByte,
                secondByte};
        MyServiceConnection.mBluetoothLeService.setCharacteristicNotificationToBliutooth(GattUpdateReceiver.bluetoothGattCharacteristicUUID_NOTIFY_WRITE_NO_RESPONSE, true, ENABLE_NOTIFICATION_MIX_VALUE2);

    }

    //获取当前手表电量
    public void sendElectricQuantit( ) {

        final byte[] ENABLE_NOTIFICATION_MIX_VALUE2 = new byte[]{0x03, (byte) 0x32, 0x00};
        MyServiceConnection.mBluetoothLeService.setCharacteristicNotificationToBliutooth(GattUpdateReceiver.bluetoothGattCharacteristicUUID_NOTIFY_WRITE_NO_RESPONSE, true, ENABLE_NOTIFICATION_MIX_VALUE2);
    }

    //找手环
    public void sendFindWatch(BluettothInterface mBluettothInterface) {
        final byte[] ENABLE_NOTIFICATION_MIX_VALUE2 = new byte[]{0x03, (byte) 0x33, 0x06};
        MyServiceConnection.mBluetoothLeService.setCharacteristicNotificationToBliutooth(GattUpdateReceiver.bluetoothGattCharacteristicUUID_NOTIFY_WRITE_NO_RESPONSE, true, ENABLE_NOTIFICATION_MIX_VALUE2);


    }
    //找手环
    public void sendFindWatch2( ) {
        final byte[] ENABLE_NOTIFICATION_MIX_VALUE2 = new byte[]{0x03, (byte) 0x33, 0x06};
        MyServiceConnection.mBluetoothLeService.setCharacteristicNotificationToBliutooth(GattUpdateReceiver.bluetoothGattCharacteristicUUID_NOTIFY_WRITE_NO_RESPONSE, true, ENABLE_NOTIFICATION_MIX_VALUE2);


    }

    //获取手表运动数据
    public void sendGetSportData() {
        final byte[] ENABLE_NOTIFICATION_MIX_VALUE2 = new byte[]{0x04, (byte) 0x35, 0x00, 0x01};
        MyServiceConnection.mBluetoothLeService.setCharacteristicNotificationToBliutooth(GattUpdateReceiver.bluetoothGattCharacteristicUUID_NOTIFY_WRITE_NO_RESPONSE, true, ENABLE_NOTIFICATION_MIX_VALUE2);


    }

    //将应用通知消息推送给手表
    public void sendApplicationInfomationToWatch(final BluettothInterface mBluettothInterface, final byte[] content) {
        //发送的数据
//        byte[] content=Myhex.hexStringToByte(Myhex.unicodeEncode("1234"));
        byte[] beforeFiveByte = null;
        beforeFiveByte = new byte[]{0x00, (byte) 0x36, 0x00, 0x01, (byte) 0x00};

        if(content.length <= 20-5){//表示一包就能发送
            //总长度
            byte[] allLength= MyByte.intToByteArray(content.length+5);
            beforeFiveByte[0]= allLength[allLength.length-1];

            //具体数据的总包
            byte[] dataByte=MyByte.intToByteArray(content.length);
            beforeFiveByte[4]= dataByte[dataByte.length-1];

            List<Byte> listNeedSend=new ArrayList<>();

            for(int i=0;i<beforeFiveByte.length;i++){
                listNeedSend.add(beforeFiveByte[i]);
            }
            for(int i=0;i<content.length;i++){
                listNeedSend.add(content[i]);
            }
            byte[] needSendByteData=new byte[listNeedSend.size()];

            for(int i=0;i<needSendByteData.length;i++){
                needSendByteData[i]=listNeedSend.get(i);
            }

            MyServiceConnection.mBluetoothLeService.setCharacteristicNotificationToBliutooth(GattUpdateReceiver.bluetoothGattCharacteristicUUID_NOTIFY_WRITE_NO_RESPONSE, true, needSendByteData);
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            BluetoothCommandCode.getCheckSendDataUtilsInstance().sendApplicationInfomationToWatchEND(mBluettothInterface);

        }else{//表示需要多包才能发送
            /****************************************第一包数据****************************************/
            //总长度
            byte[] allLength= MyByte.intToByteArray(20);
            beforeFiveByte[0]= allLength[allLength.length-1];

            //具体数据的总包
            byte[] dataByte=MyByte.intToByteArray(content.length);
            beforeFiveByte[4]= dataByte[dataByte.length-1];

            List<Byte> listNeedSend=new ArrayList<>();
            List<Byte> listSecondNeedSend=new ArrayList<>();

            for(int i=0;i<beforeFiveByte.length;i++){
                listNeedSend.add(beforeFiveByte[i]);
            }
            for(int i=0;i<content.length;i++){
                if(i<15){
                    listNeedSend.add(content[i]);
                }else{
                    listSecondNeedSend.add(content[i]);

                }
            }
            byte[] needSendByteData=new byte[listNeedSend.size()];

            for(int i=0;i<needSendByteData.length;i++){
                needSendByteData[i]=listNeedSend.get(i);
            }

            MyServiceConnection.mBluetoothLeService.setCharacteristicNotificationToBliutooth(GattUpdateReceiver.bluetoothGattCharacteristicUUID_NOTIFY_WRITE_NO_RESPONSE, true, needSendByteData);

            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            /****************************************后续包数据****************************************/

            byte[] secondByteData=new byte[listSecondNeedSend.size()];

            for(int i=0;i<listSecondNeedSend.size();i++){
                secondByteData[i]=listSecondNeedSend.get(i);
            }


            BluetoothCheckSendDataUtils.getCheckSendDataUtilsInstance().initCheckSendDataUtils(secondByteData, 20);
            byte[] needSendData = null;
            while (true) {
                needSendData = BluetoothCheckSendDataUtils.getCheckSendDataUtilsInstance().checkDataIsSatisfyMtuValus();
                if(needSendData==null||needSendData.length<=0){
                    break;
                }

                MyServiceConnection.mBluetoothLeService.setCharacteristicNotificationToBliutooth(GattUpdateReceiver.bluetoothGattCharacteristicUUID_NOTIFY_WRITE_NO_RESPONSE, true, needSendData);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            BluetoothCommandCode.getCheckSendDataUtilsInstance().sendApplicationInfomationToWatchEND(mBluettothInterface);
        }



    }

    //将应用通知消息推送给手表
    public void sendApplicationInfomationToWatchEND(BluettothInterface mBluettothInterface) {
        final byte[] ENABLE_NOTIFICATION_MIX_VALUE2 = new byte[]{0x03, (byte) 0x36, (byte) 0xfd};
        MyServiceConnection.mBluetoothLeService.setCharacteristicNotificationToBliutooth(GattUpdateReceiver.bluetoothGattCharacteristicUUID_NOTIFY_WRITE_NO_RESPONSE, true, ENABLE_NOTIFICATION_MIX_VALUE2);

    }

    //电话响铃
    public void sendPhoneCall(BluettothInterface mBluettothInterface, final int stye) {

        if(stye== TelephonyManager.CALL_STATE_RINGING){
            final byte[] ENABLE_NOTIFICATION_MIX_VALUE2 = new byte[]{0x03, (byte) 0x38, (byte) 0x81};
            MyServiceConnection.mBluetoothLeService.setCharacteristicNotificationToBliutooth(GattUpdateReceiver.bluetoothGattCharacteristicUUID_NOTIFY_WRITE_NO_RESPONSE, true, ENABLE_NOTIFICATION_MIX_VALUE2);

        }else if(stye== TelephonyManager.CALL_STATE_OFFHOOK){

        }else if(stye== TelephonyManager.CALL_STATE_IDLE){

        }
    }



    //抬腕亮屏、屏幕关闭时间、步数
    public void sendSettings(BluettothInterface mBluettothInterface) {
        //自己的每天步数设置
        String stepsString=SharedpreferencesUtils.getCheckSendDataUtilsInstance().getMovement(App.context);
        byte [] stepByte=MyByte.intToByteArray(Integer.parseInt(stepsString));

        //屏幕亮时间
        String screenTimeoutString=SharedpreferencesUtils.getCheckSendDataUtilsInstance().getScreenTimeout(App.context);
        byte [] screenTimeoutStringByte=MyByte.intToByteArray(Integer.parseInt(screenTimeoutString));

        //距离单位
        String unitsString=SharedpreferencesUtils.getCheckSendDataUtilsInstance().getUnits(App.context);
        byte[] unitsByte=MyByte.intToByteArray(Integer.parseInt(unitsString));
        //亮屏开关
        String raiseToWakeString=SharedpreferencesUtils.getCheckSendDataUtilsInstance().getRaiseToWake(App.context);
        byte[] raiseToWakeStringByte=MyByte.intToByteArray(Integer.parseInt(raiseToWakeString));
        //获取语言
        String languageString=SharedpreferencesUtils.getCheckSendDataUtilsInstance().getLanguage(App.context);
        byte[] languageByte=MyByte.intToByteArray(Integer.parseInt(languageString));

        final byte[] ENABLE_NOTIFICATION_MIX_VALUE2 = new byte[]{0x13, (byte) 0x31, (byte) 0x01,
                screenTimeoutStringByte[screenTimeoutStringByte.length-1],
                stepByte[stepByte.length-4],stepByte[stepByte.length-3],stepByte[stepByte.length-2],stepByte[stepByte.length-1],
                raiseToWakeStringByte[raiseToWakeStringByte.length-1],
                0x00,
                0x02,
                0x00,
                unitsByte[unitsByte.length-1],
                0x01,
                languageByte[languageByte.length-1],
                0x00,
                0x01,
                0x05,
                0x01
        };
        MyServiceConnection.mBluetoothLeService.setCharacteristicNotificationToBliutooth(GattUpdateReceiver.bluetoothGattCharacteristicUUID_NOTIFY_WRITE_NO_RESPONSE, true, ENABLE_NOTIFICATION_MIX_VALUE2);

    }

    //
    /************************************** ota *************************************/

    //发送ota升级请求
    public void sendOtaUpdataRequest(BluettothInterface mBluettothInterface,int chaFengBaoStyle,int flagCounts) {

//        byte[] ENABLE_NOTIFICATION_MIX_VALUE2 = CheckSendDataUtils.getCheckSendDataUtilsInstance().firstFlagData(chaFengBaoStyle, flagCounts + 1, 1, 2);
//        MyServiceConnection.mBluetoothLeService.setCharacteristicNotificationToBliutooth(GattUpdateReceiver.bluetoothGattCharacteristicUUID_NOTIFY_WRITE_NO_RESPONSE_OTA, true, ENABLE_NOTIFICATION_MIX_VALUE2);
//        String data=Myhex.buffer2String(ENABLE_NOTIFICATION_MIX_VALUE2);

    }
    //开始升级ota
    public void startUpdateOta(BluettothInterface mBluettothInterface,byte[] needBytes) {
        MyServiceConnection.mBluetoothLeService.setCharacteristicNotificationToBliutooth(GattUpdateReceiver.bluetoothGattCharacteristicUUID_NOTIFY_WRITE_NO_RESPONSE, true, needBytes);
    }

    /**************************************线程使用*************************************/


     class  MyThread extends Thread{
        @Override
        public void run() {
            synchronized (OtaUtils.class) {
                for (int i = 0; i < methodArray.length; i++) {

                    try {
                        methodArray[i].invoke(BluetoothCommandCode.getCheckSendDataUtilsInstance());
                        if (methodArray.length - 1 == i) {

                        } else {
                            Thread.sleep(500);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }



        }
    }
}
